import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { Button, ProgressBar, Chip, SegmentedButtons, TextInput } from 'react-native-paper';
import { router } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

// 预设的价值观标签
const PRESET_VALUES = [
  '家庭', '事业', '健康', '友谊', '诚信', '自由', 
  '冒险', '创新', '稳定', '公平', '尊重', '责任', 
  '独立', '合作', '成长', '慷慨', '同情', '幽默',
  '谦虚', '勇气', '智慧', '和平', '环保', '多元化'
];

export default function ValuesScreen() {
  const colorScheme = useColorScheme();
  const { userInfo, userToken, updateProfile } = useAuth();
  const tintColor = Colors[colorScheme ?? 'light'].tint;

  // 表单状态
  const [values, setValues] = useState<string[]>(userInfo?.values || []);
  const [religion, setReligion] = useState(userInfo?.religion || '');
  const [politicalView, setPoliticalView] = useState(userInfo?.politicalView || '');
  const [relationshipGoal, setRelationshipGoal] = useState(userInfo?.relationshipGoal || '');
  const [customValue, setCustomValue] = useState('');
  const [languageInput, setLanguageInput] = useState('');
  const [languages, setLanguages] = useState<string[]>(userInfo?.languages || []);
  const [isLoading, setIsLoading] = useState(false);

  // 如果用户未登录，重定向到登录页面
  useEffect(() => {
    if (!userToken) {
      router.replace('/auth/login');
    }
  }, [userToken]);

  // 添加价值观
  const toggleValue = (value: string) => {
    if (values.includes(value)) {
      setValues(values.filter(v => v !== value));
    } else {
      setValues([...values, value]);
    }
  };

  // 添加自定义价值观
  const addCustomValue = () => {
    if (customValue.trim() && !values.includes(customValue.trim())) {
      setValues([...values, customValue.trim()]);
      setCustomValue('');
    }
  };

  // 添加语言
  const addLanguage = () => {
    if (languageInput.trim() && !languages.includes(languageInput.trim())) {
      setLanguages([...languages, languageInput.trim()]);
      setLanguageInput('');
    }
  };

  // 移除语言
  const removeLanguage = (language: string) => {
    setLanguages(languages.filter(l => l !== language));
  };

  // 处理表单提交
  const handleSubmit = async () => {
    setIsLoading(true);
    try {
      // 更新用户价值观信息
      const success = await updateProfile({
        values,
        religion,
        politicalView,
        relationshipGoal,
        languages
      });

      if (success) {
        // 进入下一步
        router.push('/profile-setup/preferences');
      } else {
        Alert.alert('错误', '更新个人资料失败，请重试');
      }
    } catch (error) {
      console.error('Update profile error:', error);
      Alert.alert('错误', '发生未知错误，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.header}>
            <ThemedText style={styles.title}>价值观与目标</ThemedText>
            <ThemedText style={styles.subtitle}>
              告诉我们您的价值观和交友目标，帮助我们找到与您理念相符的人
            </ThemedText>
          </View>

          <ProgressBar 
            progress={5/6} 
            color={tintColor} 
            style={styles.progressBar} 
          />

          <View style={styles.formContainer}>
            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>重要的价值观 (已选择 {values.length})</ThemedText>
              <ThemedText style={styles.subLabel}>选择对您来说最重要的价值观</ThemedText>
              
              <View style={styles.chipContainer}>
                {PRESET_VALUES.map((value, index) => (
                  <Chip
                    key={index}
                    selected={values.includes(value)}
                    onPress={() => toggleValue(value)}
                    style={[
                      styles.chip,
                      values.includes(value) && { backgroundColor: tintColor + '20' }
                    ]}
                    textStyle={[
                      styles.chipText,
                      values.includes(value) && { color: tintColor }
                    ]}
                  >
                    {value}
                  </Chip>
                ))}
              </View>

              <View style={styles.inputWithButton}>
                <TextInput
                  value={customValue}
                  onChangeText={setCustomValue}
                  mode="outlined"
                  placeholder="添加自定义价值观"
                  style={styles.customInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  onSubmitEditing={addCustomValue}
                />
                <Button
                  mode="contained"
                  onPress={addCustomValue}
                  style={styles.addButton}
                  theme={{ roundness: 10 }}
                >
                  添加
                </Button>
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>宗教信仰</ThemedText>
              <SegmentedButtons
                value={religion}
                onValueChange={setReligion}
                buttons={[
                  { value: 'none', label: '无' },
                  { value: 'buddhism', label: '佛教' },
                  { value: 'christianity', label: '基督教' },
                  { value: 'islam', label: '伊斯兰教' },
                  { value: 'other', label: '其他' }
                ]}
                multiline
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>政治观点</ThemedText>
              <SegmentedButtons
                value={politicalView}
                onValueChange={setPoliticalView}
                buttons={[
                  { value: 'liberal', label: '自由派' },
                  { value: 'moderate', label: '中间派' },
                  { value: 'conservative', label: '保守派' },
                  { value: 'apolitical', label: '不关心政治' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>交友目的</ThemedText>
              <SegmentedButtons
                value={relationshipGoal}
                onValueChange={setRelationshipGoal}
                buttons={[
                  { value: 'casual', label: '随意交友' },
                  { value: 'serious', label: '认真恋爱' },
                  { value: 'marriage', label: '婚姻导向' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>语言能力</ThemedText>
              <ThemedText style={styles.subLabel}>您会说哪些语言？</ThemedText>
              
              <View style={styles.inputWithButton}>
                <TextInput
                  value={languageInput}
                  onChangeText={setLanguageInput}
                  mode="outlined"
                  placeholder="例如：中文、英语、日语"
                  style={styles.customInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  onSubmitEditing={addLanguage}
                />
                <Button
                  mode="contained"
                  onPress={addLanguage}
                  style={styles.addButton}
                  theme={{ roundness: 10 }}
                >
                  添加
                </Button>
              </View>

              <View style={styles.chipContainer}>
                {languages.map((language, index) => (
                  <Chip
                    key={index}
                    onClose={() => removeLanguage(language)}
                    style={styles.chip}
                    textStyle={styles.chipText}
                  >
                    {language}
                  </Chip>
                ))}
              </View>
            </View>
          </View>

          <View style={styles.buttonContainer}>
            <Button
              mode="contained"
              onPress={handleSubmit}
              style={styles.button}
              labelStyle={styles.buttonText}
              loading={isLoading}
              disabled={isLoading}
              theme={{ roundness: 10 }}
            >
              下一步
            </Button>

            <Button
              mode="outlined"
              onPress={() => router.back()}
              style={[styles.button, styles.backButton]}
              labelStyle={styles.backButtonText}
              theme={{ roundness: 10 }}
            >
              返回
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 20,
  },
  header: {
    marginTop: 40,
    marginBottom: 30,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    opacity: 0.7,
    marginBottom: 10,
  },
  progressBar: {
    height: 8,
    borderRadius: 4,
    marginBottom: 30,
  },
  formContainer: {
    marginBottom: 30,
  },
  formGroup: {
    marginBottom: 25,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
    fontWeight: '500',
  },
  subLabel: {
    fontSize: 14,
    marginBottom: 12,
    opacity: 0.7,
  },
  segmentedButtons: {
    marginBottom: 10,
  },
  chipContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 15,
  },
  chip: {
    margin: 4,
  },
  chipText: {
    fontSize: 14,
  },
  inputWithButton: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  customInput: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  addButton: {
    marginLeft: 10,
  },
  buttonContainer: {
    marginTop: 'auto',
    marginBottom: 20,
  },
  button: {
    marginBottom: 15,
    paddingVertical: 8,
  },
  buttonText: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  backButton: {
    borderColor: '#ccc',
  },
  backButtonText: {
    fontSize: 16,
  },
});
